<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :excludeValues="['namespace']"
      v-model:form-value="state.query"
      :table-column="columns"
      :defaultFormNum="6"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="cacheEname" label="缓存名称">
          <!-- <FIInput v-model="state.query.cacheEname" clearable /> -->
          <FISelect
            v-if="arr2.length > 0"
            @change="onCellChange"
            v-model="state.query.cacheEname"
            valueCustom="cacheEname"
            :props="{
              value: 'cacheEname',
              label: 'cacheCname',
            }"
            :display-key="['cacheEname', 'cacheCname']"
            :options="arr2"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="remark" label="备注">
          <FIInput v-model="state.query.remark" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="P1" label="参数1">
          <FIInput v-model="state.query.P1" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="P2" label="参数2">
          <FIInput v-model="state.query.P2" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="P3" label="参数3">
          <FIInput v-model="state.query.P3" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="P4" label="参数4">
          <FIInput v-model="state.query.P4" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :insertable="false"
      :data="state.dataList"
      primaryKey="key"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :showPageBar="false"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      checkMode=""
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleAction"
    >
      <template #headerBtn>
        <!-- <FIButton id="b3333"></FIButton> -->
        <!-- <FIButton @click="isVisible = !isVisible">model</FIButton> -->

        <FIPopconfirmBtn
          title="您是否确认清空缓存吗？"
          buttonText="清空缓存"
          :btn-binds="{ id: 'clearData', border: true }"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
        <!-- <FIPopconfirmBtn
          title="您是否确认要刷新缓存？"
          buttonText="刷新缓存"
          api-url="/pageMaint/refreshCache"
          :btn-binds="{ customType: 'border' }"
        >
        </FIPopconfirmBtn> -->
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, getHasSearchValues } from '@/utils/common'

import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiGetcacheMaint } from '@/api/configEnvMaint/index.ts'
import { ElMessage, ElMessageBox } from 'element-plus'

import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const isVisible = ref(false)
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'codesetMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)

const state = reactive({
  query: {
    cacheEname: '',
    remark: '',
    namespace: '',
    P1: '',
    P2: '',
    P3: '',
    P4: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const columns: Column[] = reactive([
  {
    label: 'KEY',
    prop: 'key',
    align: 'center',

    // editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: 'VALUE',
    prop: 'value',
    align: 'center',

    // editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [
      { id: 'deleteData', type: 'action_deleteData' },
      // { id: 'b5555', type: 'add' },
    ],
    // isCustomAction: true,
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleAction = (item, rowData, butoninfo) => {
  ElMessageBox.confirm('您是否确认删除当前数据吗?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      let params = [state.query.P1, state.query.P2, state.query.P3, state.query.P4].filter(Boolean) // 过滤掉所有假值，只剩下真值（非空且非零的值）

      // 如果所有 P1 到 P4 都为空或未定义，此时 params 会是空数组
      if (params.length === 0) {
        // params 保持为空数组，表示没有任何参数
      } else {
        // 否则，将所有有效的值用逗号连接成一个字符串，然后又将其分割成数组（这一步其实没有必要，直接使用 params 即可）
        // params = params.join(',').split(',');
      }
      let data = {
        namespace: state.query.namespace,
        cacheEname: state.query.cacheEname + '::' + rowData.key,
        params: params,
      }
      const apiUrl = proxy.$Button_api('deleteData', route.name)
      apiRequestPost(apiUrl, data)
        // apiRequestPost('/rm2/cacheMaint/deleteData', data)
        .then((res) => {
          isTableLoading.value = false
          searchFn()
        })
        .catch((error: any) => {
          isTableLoading.value = false
        })
      ElMessage({
        type: 'success',
        message: '删除成功!',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })

  // if (item.id) {
  //     useMessage().warning('请选择一条数据')
  //     return
  //   }
  // postShow.value = true
  // selectedNode.value=rowData
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  if (!state.query.cacheEname) {
    useMessage().warning('请选缓存名称')
    return
  }
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  let params = [state.query.P1, state.query.P2, state.query.P3, state.query.P4].filter(Boolean) // 过滤掉所有假值，只剩下真值（非空且非零的值）

  // 如果所有 P1 到 P4 都为空或未定义，此时 params 会是空数组
  if (params.length === 0) {
    // params 保持为空数组，表示没有任何参数
  } else {
    // 否则，将所有有效的值用逗号连接成一个字符串，然后又将其分割成数组（这一步其实没有必要，直接使用 params 即可）
    // params = params.join(',').split(',');
  }
  let data = {
    namespace: state.query.namespace,
    cacheEname: state.query.cacheEname,
    params: params,
  }
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, data)
    // apiRequestPost('/rm2/cacheMaint/getData', data)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        if (res.data.data.type === 'list' || res.data.data.type === 'set') {
          let newArray = [res.data.data]
          console.log(newArray)
          let keyValuePairsArray = newArray[0].cacheData.map((value, index) => ({ key: ``, value }))
          keyValuePairsArray.forEach((item, index) => {
            item.dynamicActionConfig = [
              { id: 'action_deleteData', type: 'action_deleteData', hidden: true, disabled: true },
            ]
          })
          state.dataList = keyValuePairsArray
          console.log(res.data.data)
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        } else if (res.data.data.type === 'string') {
          // let parsedData = JSON.parse(res.data.data.cacheData)
          if (res.data.data.cacheData) {
            let keyValueArray = []
            // keyValueArray.push({ key: '', value: '“' + JSON.stringify(res.data.data.cacheData) + '”' })
            keyValueArray.push({ key: '', value: res.data.data.cacheData })
            keyValueArray.forEach((item, index) => {
              item.dynamicActionConfig = [
                { id: 'action_deleteData', type: 'action_deleteData', hidden: true, disabled: true },
              ]
            })
            console.log(keyValueArray, '============')
            state.dataList = keyValueArray
          } else {
            state.dataList = []
          }
        } else if (res.data.data.type === 'hash') {
          let keyValuePairs = Object.entries(res.data.data.cacheData).map(([key, value]) => {
            try {
              let parsedValue = typeof value === 'string' && value.trim() !== '' ? JSON.parse(value) : value
              return { key: `'${key}'`, value: parsedValue }
            } catch (error) {
              console.error(`无法解析键 ${key} 的值，保持原样：${value}`)
              return { key: `'${key}'`, value }
            }
          })
          keyValuePairs.forEach((item, index) => {
            item.dynamicActionConfig = [
              { id: 'action_deleteData', type: 'action_deleteData', hidden: false, disabled: false },
            ]
          })
          state.dataList = keyValuePairs
        } else if (res.data.data.type === 'none') {
          state.dataList = []
          // ElMessage.error('用户缓存不存在')
        }
      } else {
        state.dataList = []
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  const apiUrl = proxy.$Button_api('saveCodeset', route.name)
  apiRequestPost(apiUrl, checkedRows.value)
    // apiRequestPost('/rm2/codesetMaint/saveCodeset', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow = () => {
  // if (!checkedRows.value.length) {
  //   useMessage().warning('请选择一条数据')
  //   return
  // }
  // let ids = []
  // Array.isArray(checkedRows.value) &&
  //   checkedRows.value.forEach((item: any) => {
  //     if (item?.codesetId) ids.push(item?.codesetId)
  //   })
  // isTableLoading.value = true
  let params = [state.query.P1, state.query.P2, state.query.P3, state.query.P4].filter(Boolean) // 过滤掉所有假值，只剩下真值（非空且非零的值）

  // 如果所有 P1 到 P4 都为空或未定义，此时 params 会是空数组
  if (params.length === 0) {
    // params 保持为空数组，表示没有任何参数
  } else {
    // 否则，将所有有效的值用逗号连接成一个字符串，然后又将其分割成数组（这一步其实没有必要，直接使用 params 即可）
    // params = params.join(',').split(',');
  }
  let data = {
    namespace: state.query.namespace,
    cacheEname: state.query.cacheEname,
    params: params,
  }
  const apiUrl = proxy.$Button_api('clearData', route.name)
  apiRequestPost(apiUrl, data)
    // apiRequestPost('/rm2/cacheMaint/deleteData', data)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        ElMessage.success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)
watch(
  () => columns.values,
  (newValue) => {},
  { deep: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
const arr2 = ref([])
const getProjectname = () => {
  apiGetcacheMaint().then((res) => {
    // console.log(res.data.data,99999999999999999999)
    if (res.data.success) {
      // Array.isArray(res.data.data) &&
      //   res.data.data.forEach((item) => {
      //     // item.label = item.moduleCname2
      //     item.label = `[${item.cacheCname}] ${item.cacheEname}`
      //     item.value = item.remark
      //   })
      if (Array.isArray(res.data.data)) {
        // const newArray = res.data.data.map((item) => ({
        //   label: `【${item.cacheCname}】${item.cacheEname}`,
        //   value: item.remark,
        // }));

        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr2.value = res.data.data
        console.log(arr2.value, 'llllll')
      }
    }
  })
}

const onCellChange = (e) => {
  console.log(e, 'pppplllll')
  const selectedOptionValue = e
  // const selectedOptionData = arr2.value.find((row) => row.value === selectedOptionValue);
  const selectedOptionData = arr2.value.find((item) => item.cacheEname === selectedOptionValue)
  console.log(selectedOptionData, 'ppppppp')
  state.query.namespace = selectedOptionData?.namespace
  state.query.remark = selectedOptionData?.remark
  state.query.cacheEname = selectedOptionData?.cacheEname

  // getProjectname()
}
watch(
  () => state.query.cacheEname,
  (newVal) => {
    if (!newVal) {
      state.query.namespace = ''
    }
  }
)
onMounted(() => {
  getProjectname()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()
})
</script>
<style lang="less" scoped></style>
